<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >库存管理(财务)</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/inventoryManagement/transferFinanceWarehousing/whole'
          }"
          >运输财务入库管理</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: toUrl }">{{
          pathName
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">编辑</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <basicInformation
              ref="formDateBUI"
              :storageForm="storageForm"
              :tranStorageBObj="tranStorageBObj"
              :associationList="associationList"
              @association="association"
              @updataList="updataList"
              @getAssociationList="getAssociationList"
            ></basicInformation>
          </el-tab-pane>
          <el-tab-pane label="采购清单" name="second">
            <contractList
              ref="contractList"
              :storage-list="finStorageList"
              :storageForm="storageForm"
              @delectList="delectList"
            ></contractList>
          </el-tab-pane>
          <el-tab-pane label="关联入库单" name="third" v-if="isHideAssociation">
            <associationWarehousing
              ref="association"
              :storage-list="associationList"
            ></associationWarehousing>
          </el-tab-pane>
          <el-tab-pane label="附件" name="fourth">
            <upload-info
              v-if="isTrue"
              ref="contractAppendix"
              isTab
              v-model="fileList"
              title="合同附件"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="saveTranStorage"
            >暂存</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-cancel"
            @click="submitHandle('submit')"
            >保存并提交</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="resetHandle"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import basicInformation from "./edit/basicInformation";
import UploadInfo from "@/basa/components/public/uploadInfo2";
import contractList from "./edit/contractList";
import associationWarehousing from "./edit/association-warehousing.vue";
import {
  getTranStorage,
  editTranStorage,
  submitTranStorage,
  saveTranStorage
} from "../api/edit-item";
import { ishasAgentId } from "@/basa/utils";
import peopleManage from "../mixins/peopleManage";
export default {
  name: "edit-item",
  mixins: [peopleManage],
  components: {
    basicInformation,
    UploadInfo,
    contractList,
    associationWarehousing
  },
  data() {
    return {
      storageForm: {
        count: 0,
        settlementCount: 0,
        moneyWithTax: 0
      },
      finStorageList: [],
      activeName: "first",
      submitFlag: false,
      taxRate: 0,
      focus: "formDateBUI",
      fileList: [], // 附件上传集合
      isTrue: false,
      BillData: [], //总数组2
      contractListBool: false, //校验变更列表是否为空
      isHideAssociation: true, //控制影藏关联入库单页签
      associationList: [], //关联入库单数据列表
      tranStorageBObj: {}
    };
  },
  watch: {
    $route(to, form) {
      console.log(to);
      if (to.name == "transport-inventory-financeWarehousing-edit-item") {
        this.getTranStorage();
      }
    }
  },
  created() {
    sessionStorage.setItem("thirdCategoriesOfName", "");
    this.getTranStorage();
  },
  methods: {
    association(val) {
      this.isHideAssociation = val;
    },
    updataList(val) {
      this.finStorageList = val;
    },
    delectList(val) {
      this.finStorageList = val.filter((item) => item.check != true);
    },
    getAssociationList(data) {
      this.associationList = data;
    },
    handleClick(tab, event) {
      console.log(tab, event, this.activeName);
      this.activeName = tab.name;
    },
    // 暂存
    saveTranStorage() {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach((row) => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });

      let finStorageList = this.finStorageList;
      finStorageList.forEach((item) => {
        item.storageCount = item.storageCount ? item.storageCount : "0.000";
      });

      let associationList = this.associationList;

      let obj = {
        tranStorageBO: this.$refs.formDateBUI.form,
        fileBOList: this.fileList1,
        tranStorageListBOList: finStorageList,
        tranStorageRelBOList: associationList,
        isShowLoading: true
      };

      //对下计价
      if (obj.tranStorageBO.finType == "1") {
        obj.tranStorageBO.refStorageCodeString = "";
        obj.tranStorageBO.refStorageIdString = "";
        obj.tranStorageBO.warehouseName = "";
        obj.tranStorageBO.warehouseCode = "";
        obj.tranStorageBO.warehouseId = "";
        //运输产品分类 固定存取选择结算单后的物资三级分类名称
        obj.tranStorageBO.thirdCategoriesOfName =
          obj.tranStorageBO.thirdCategoriesOfName1;

        obj.tranStorageRelBOList = [];
      }

      this.$loading({
        lock: true,
        text: "暂存中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      saveTranStorage(obj)
        .then((res) => {
          this.$loading().close();
          let { code } = res.data;
          this.$message({
            message: "暂存成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch((e) => {
          this.$loading().close();
          console.log(e);
        });
    },
    // 保存 提交
    submitHandle(name) {
      this.getValidate(this.finStorageList);
      this.$refs.formDateBUI.$refs.form.validate((valid) => {
        if (valid) {
          if (this.contractListBool) {
            // 调接口
            if (name == "save") {
              this.editTranStorage(name);
            } else {
              this.submitTranStorage(name);
            }
          } else {
            // 弹个窗
            this.$message({
              type: "error",
              message: this.messageCount,
              showClose: true,
              ccuiCustom: true
            });
          }
        } else {
          this.$showErrorMessage("入库单基本信息不完整，请编辑后保存");
          this.activeName = "first";
        }
      });
    },
    // edit详情
    getTranStorage() {
      let obj = {
        id: parseInt(this.$route.params.id),
        storageType: parseInt(this.$route.query.storageType)
      };
      getTranStorage(obj).then((res) => {
        let tranStorageBO = res.data.data.tranStorageBO;
        tranStorageBO.finType = tranStorageBO.finType + "";
        this.$refs.formDateBUI.form = tranStorageBO;
        if (tranStorageBO.thirdCategoriesOfName != "运输服务") {
          sessionStorage.setItem(
            "thirdCategoriesOfName",
            tranStorageBO.thirdCategoriesOfName
          );
        }
        if (tranStorageBO.finType == "1") {
          tranStorageBO.thirdCategoriesOfName = "运输服务";
        }
        this.tranStorageBObj = tranStorageBO;
        this.finStorageList = res.data.data.tranStorageListBOList;
        this.finStorageList.forEach((item) => {
          item.moneyWithTax = item.moneyWithTax
            ? item.moneyWithTax.toFixed(2)
            : "";
          item.unStorageCount = item.unStorageCount
            ? item.unStorageCount.toFixed(3)
            : "";
          item.storageCount = item.storageCount
            ? item.storageCount.toFixed(3)
            : "";
          item.unitPriceWithTax = item.unitPriceWithTax
            ? item.unitPriceWithTax.toFixed(2)
            : "";
          item.moneyWithoutTax = item.moneyWithoutTax
            ? item.moneyWithoutTax.toFixed(2)
            : "";
        });
        this.fileList = res.data.data.fileBOList;
        this.fileList.forEach((item) => {
          item.createTimeStr = item.createTime;
          item.uploadId = item.fileInfoId;
          item.fileSize =
            Number(item.fileSize.substr(0, item.fileSize.length - 2)) * 1024;
        });
        this.associationList = res.data.data.tranStorageRelBOList;
        this.associationList.forEach((item) => {
          item.storageCount = item.storageCount
            ? item.storageCount.toFixed(3)
            : "";
          item.storageMoney = item.storageMoney
            ? item.storageMoney.toFixed(2)
            : "";
        });

        this.isTrue = true;
      });
    },
    // 保存/提交
    editTranStorage(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach((row) => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });

      let finStorageList = this.finStorageList;
      finStorageList.forEach((item) => {
        item.storageCount = item.storageCount ? item.storageCount : "0.000";
      });

      let associationList = this.associationList;

      let obj = {
        tranStorageBO: this.$refs.formDateBUI.form,
        fileBOList: fileList1,
        tranStorageListBOList: finStorageList,
        tranStorageRelBOList: associationList,
        isShowLoading: true,
        loadingMessage: "保存中,请稍等..."
      };

      if (this.$route.query.form == "back") {
        obj.tranStorageBO.storageStatus = 6;
      }

      //对下计价
      if (obj.tranStorageBO.finType == "1") {
        obj.tranStorageBO.refStorageCodeString = "";
        obj.tranStorageBO.refStorageIdString = "";
        obj.tranStorageBO.warehouseName = "";
        obj.tranStorageBO.warehouseCode = "";
        obj.tranStorageBO.warehouseId = "";
        //运输产品分类 固定存取选择结算单后的物资三级分类名称
        obj.tranStorageBO.thirdCategoriesOfName =
          obj.tranStorageBO.thirdCategoriesOfName1;

        obj.tranStorageRelBOList = [];
      }

      editTranStorage(obj)
        .then((res) => {
          let { code, message } = res.data;
          this.$message({
            message: message,
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    submitTranStorage(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach((row) => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });

      let finStorageList = this.finStorageList;
      finStorageList.forEach((item) => {
        item.storageCount = item.storageCount ? item.storageCount : "0.000";
      });

      let associationList = this.associationList;

      let obj = {
        tranStorageBO: this.$refs.formDateBUI.form,
        fileBOList: fileList1,
        tranStorageListBOList: finStorageList,
        tranStorageRelBOList: associationList,
        isShowLoading: true,
        loadingMessage: "提交中,请稍等..."
      };

      //对下计价
      if (obj.tranStorageBO.finType == "1") {
        obj.tranStorageBO.refStorageCodeString = "";
        obj.tranStorageBO.refStorageIdString = "";
        obj.tranStorageBO.warehouseName = "";
        obj.tranStorageBO.warehouseCode = "";
        obj.tranStorageBO.warehouseId = "";
        //运输产品分类 固定存取选择结算单后的物资三级分类名称
        obj.tranStorageBO.thirdCategoriesOfName =
          obj.tranStorageBO.thirdCategoriesOfName1;

        obj.tranStorageRelBOList = [];
      }

      submitTranStorage(obj)
        .then((res) => {
          let { code, message } = res.data;
          this.$message({
            message: message,
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 校验变更列表不能为空
    getValidate(data) {
      let newArr = data.filter((item) => item.relationList);
      let newArrTow = [];
      newArr.forEach((item) => {
        if (item.isOtherCost == 1 || item.isServices == 1) {
          newArrTow.push(item);
        }
      });
      console.log(newArrTow);
      let a = [];
      newArrTow.forEach((item) => {
        if (item.materialCode == "") {
          return a.push(item.materialName);
        } else if (item.materialCode && item.materialCode != "") {
          return (this.messageCount =
            "设备物资编码" + item.materialCode + ",请关联入库单");
        }
      });
      if (a.length > 0) {
        this.messageCount = a.join(",请关联入库单; ") + ",请关联入库单;";
      }
      this.contractListBool = newArrTow.every((item) => {
        return item.relationList.length;
      });
    },
    // 取消
    resetHandle() {
      this.handleBack();
    },
    handleBack() {
      // this.$router.push(
      //   sessionStorage.getItem("fromPath") ||
      //     "/contracts/contractChangeEntry/un-submitted"
      // );
      this.$router.go(-1);
    },
    tabChange(item, index) {
      this.focus = item[0];
      this.$refs[item[0]].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start" // 上边框与视窗顶部平齐。默认值
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log(from);
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    next();
  }
};
</script>

<style lang="scss" scoped>
/deep/.extend-btn {
  text-align: right;
  margin-bottom: 15px;
  top: 0px;
  position: relative !important;
}
/deep/.ccui-form {
  margin-top: 0px;
}
.detail-info {
  width: calc(100% - 438px);
  min-height: calc(100vh - 260px);
  float: left;
  background: #fff;
  position: relative;
  padding: 14px 20px 0 20px;
  margin: 15px 0 80px;
}
/deep/.el-table td,
.el-table th {
  padding: 0 0;
  height: 36px;
}
/deep/.el-col-13 {
  width: 79%;
}

/deep/.detail-info-el-Label {
  position: absolute;
  width: 107px;
  right: 50px;
  top: 31px;
  z-index: 1;
}

.el-none {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  white-space: normal;
  word-break: break-all;
  word-wrap: break-word;
}
/deep/.extend-btn {
  text-align: right;
  margin-bottom: 15px;
  top: 0px;
  position: relative !important;
}
/deep/.ccui-form {
  margin-top: 0px;
}
/deep/ .ccui-multifunctional-table-wrapper {
  .el-table td,
  .el-table th.is-leaf {
    border-right: 1px solid #edf2fc;
  }
}

/deep/ .el-table__footer-wrapper {
  margin-top: 0px;
}
// 表格合计行样式
/deep/.el-table__footer {
  width: 100% !important;
}

// 解决表格定位滚动条无法拖动
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}
/deep/ .el-table__fixed,
/deep/.el-table__fixed-right {
  pointer-events: none;
  td {
    pointer-events: auto;
  }
}
/deep/.el-table--border {
  th:last-of-type.gutter {
    display: table-cell !important;
    width: 0px !important;
  }
}
/deep/
  .ccui-multifunctional-table-wrapper
  .el-table
  tbody
  tr
  td:last-child
  .cell {
  padding-right: 5px !important;
}
</style>
